const Controller = require('egg').Controller;
const fs = require('fs');
const path = require('path');
const request = require('request');
const ErrorUtil = require('../../class/error');
module.exports = app => {
  return class ResourceController extends Controller {
    async parseFdp() {
      const ctx = this.ctx;
      const query = ctx.query;
      const resourceId = query.resourceId;
      const resource = await this.service.resource.selectById(resourceId);
      if (resource.type == 2 && resource.mime == "application/pdf") {
        ctx.locals = {
          resource: resource,
        }
      } else {
        ctx.locals = {
          error: ErrorUtil.FILETYPEERROR,
        }
      }
      await ctx.render('front/resource/pdf_view.html');
    }

    /**
     * @description 文档下载
     * @author xiezuobing[948466]<435321508@qq.com>
     */
    async downloadFile() {
      try {
        await this.service.resource.update({
          id: this.ctx.query.resourceId,
          download: app.Sequelize.literal('`download` +1')
        })
        const resource = await this.service.resource.selectById(this.ctx.query.resourceId);
        let filePath = path.join(app.config.root, resource.url);
        this.ctx.attachment(resource.name);
        this.ctx.set('Content-Type', 'application/octet-stream');
        await this.service.operationLog.create(
          app.config.operationType.type.DOWNLOAD, 
          app.config.operationType.target.RESOURCE,
          resource.id,
          this.ctx.session.frontUser.user_id,
         );
        this.ctx.body = fs.createReadStream(filePath);
      } catch (e) {
        this.ctx.body = ErrorUtil.UNKOWN;
        throw e;
      }
    }


    /**
     * @description 查看文档
     * @author xiezuobing[948466]<435321508@qq.com>
     */
    async viewFile(){
      const ctx = this.ctx;
      await this.service.resource.update({
        id: ctx.query.resourceId,
        view: app.Sequelize.literal('`view` +1')
      })
      const resource = await this.service.resource.selectById(this.ctx.query.resourceId);
      await this.service.operationLog.create(
        app.config.operationType.type.VIEW, 
        app.config.operationType.target.RESOURCE,
        resource.id,
        ctx.session.frontUser.user_id
      );
      ctx.locals = {
        file: resource,
      }
      await ctx.render('front/resource/pdf_viewer.html');
    }
  }
}